今天是鐵人賽的第八天唷!想不到一下子就八天過去了!
每個被封裝元件,都有自己模板、樣式和行為。
這裡來說說在vue的實體時data總是以一個物件來表示,在子元件的data則以函數回傳物件來表示,因為JavaScript的物件型別以傳址進行資料傳遞,如果沒透過function回傳另個新物件,這些data就會共用一個狀態。
呈現如下:
<div id="app">
    <example-component></example-component>
    <example-component></example-component>
</div>
const app = Vue.createApp({ });
//共用data
const $data = {
  example: 0
};
//共用$data非各自獨立
app.component('example-component', {
    template: `
        <div>{{ example }}</div>
        <button @click="example++">+1</button>`
    data(){
        return $data;
    }
});
app.mount('#app');
//用function方式
app.component('example-component', {
    template: `
        <div>{{ example }}</div>
        <button @click="example++">+1</button>`
    data: function () {
        return {
            example: 0
        }
    }
});
//沒用this則可使用箭頭函式回傳一個新物件
app.component('example-component', {
    template: `
        <div>{{ example }}</div>
        <button @click="example++">+1</button>`
    data: () => {{ example: 0 })
});
這樣子元件狀態就會各自獨立了!
以上為今天的鐵人賽文章謝謝閱讀。